import type { CSSProperties } from 'vue';
import { isNumber } from './is';
// import { ref, onBeforeUpdate } from 'vue';
export interface ModuleStyleConfig {
  styles?: CSSProperties;
  width?: number;
  height?: number;
  padding?: number[];
}

export const unitToRem = (px?: number) => {
  if (!isNumber(px)) return;
  const rem = parseFloat(getComputedStyle(window.document.documentElement)['font-size']) || 16;
  return px / rem;
};

export function setStyle(style: ModuleStyleConfig): CSSProperties {
  const { width, height, padding = [] } = style;

  let pt;
  let pr;
  let pb;
  let pl;

  const paddingLen = padding.length;
  if (paddingLen) {
    const [top, right, bottom, left] = padding;
    switch (paddingLen) {
      case 1:
        pt = unitToRem(top);
        break;
      case 2:
        pt = unitToRem(top);
        pr = unitToRem(right);
        break;
      case 3:
        pt = unitToRem(top);
        pr = unitToRem(right);
        pb = unitToRem(bottom);
        break;
      case 4:
        pt = unitToRem(top);
        pr = unitToRem(right);
        pb = unitToRem(bottom);
        pl = unitToRem(left);
        break;
    }
  }

  const styleOjb = {
    width: `${unitToRem(width)}rem`,
    height: `${unitToRem(height)}rem`,
    paddingTop: `${pt}rem`,
    paddingRight: `${pr}rem`,
    paddingBottom: `${pb}rem`,
    paddingLeft: `${pl}rem`,
  };

  delProps(styleOjb);

  return styleOjb;
}

function delProps(styleOjb: Indexable) {
  for (const [k, v] of Object.entries(styleOjb)) {
    if (v.includes('undefined')) {
      delete styleOjb[k];
    }
  }
}
